<template>
  <div class="permission-management">
    <el-tree
      ref="permissionTree"
      :data="permissionList"
      show-checkbox
      node-key="id"
      :default-checked-keys="checkedKeys"
      :props="defaultProps"
      @check-change="handleCheckChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getPermissionTree, updateRolePermissions } from '@/api/permission'

const props = defineProps<{
  roleId: number
}>()

const permissionList = ref([])
const checkedKeys = ref([])

const defaultProps = {
  children: 'children',
  label: 'permissionName'
}

onMounted(async () => {
  try {
    const { data } = await getPermissionTree()
    permissionList.value = data
    // 获取角色已有权限
    const rolePerms = await getRolePermissions(props.roleId)
    checkedKeys.value = rolePerms.map(p => p.id)
  } catch (error) {
    console.error('获取权限树失败:', error)
  }
})

const handleCheckChange = async (data: any, checked: boolean) => {
  try {
    const checkedNodes = permissionTree.value.getCheckedNodes()
    const permissionIds = checkedNodes.map(node => node.id)
    await updateRolePermissions(props.roleId, permissionIds)
    ElMessage.success('权限更新成功')
  } catch (error) {
    console.error('更新权限失败:', error)
    ElMessage.error('权限更新失败')
  }
}
</script> 